from mcp.server.fastmcp import FastMCP, Context
import subprocess
import json
from typing import Dict, Any

mcp = FastMCP("Bluez MCP Server")

"""
Bluez MCP Server

面向 bluez 蓝牙软件栈的命令行操作 MCP 服务。

MCP tools 列表：
1. bluetooth_mesh_service_control - 控制 bluetooth-mesh 服务
   用途：启动、停止、重启或重载 bluetooth-mesh 服务
   参数：action (str) - 操作类型：start/stop/restart/reload
   返回：统一 JSON 结构

2. bluetooth_service_control - 控制 bluetooth 服务
   用途：启动、停止、重启或重载 bluetooth 服务
   参数：action (str) - 操作类型：start/stop/restart/reload
   返回：统一 JSON 结构
"""

@mcp.tool()
def bluetooth_mesh_service_control(action: str) -> Dict[str, Any]:
    """
    控制 bluetooth-mesh 服务的启动、停止、重启和重载操作

    参数:
        action: 操作类型，可选值：start（启动）、stop（停止）、restart（重启）、reload（重载）

    返回 JSON 结构:
        {
            "success": bool,      # 操作是否成功
            "command": str,       # 执行的完整命令
            "exit_code": int,     # 命令退出码
            "stdout": str,        # 标准输出
            "stderr": str         # 标准错误
        }
    """
    valid_actions = ["start", "stop", "restart", "reload"]
    if action not in valid_actions:
        return {
            "success": False,
            "command": f"systemctl {action} bluetooth-mesh.service",
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Invalid action: {action}. Must be one of {valid_actions}"
        }
    
    command = f"systemctl {action} bluetooth-mesh.service"
    try:
        result = subprocess.run(
            command.split(),
            capture_output=True,
            text=True,
            timeout=30
        )
        return {
            "success": result.returncode == 0,
            "command": command,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def bluetooth_service_control(action: str) -> Dict[str, Any]:
    """
    控制 bluetooth 服务的启动、停止、重启和重载操作

    参数:
        action: 操作类型，可选值：start（启动）、stop（停止）、restart（重启）、reload（重载）

    返回 JSON 结构:
        {
            "success": bool,      # 操作是否成功
            "command": str,       # 执行的完整命令
            "exit_code": int,     # 命令退出码
            "stdout": str,        # 标准输出
            "stderr": str         # 标准错误
        }
    """
    valid_actions = ["start", "stop", "restart", "reload"]
    if action not in valid_actions:
        return {
            "success": False,
            "command": f"systemctl {action} bluetooth.service",
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Invalid action: {action}. Must be one of {valid_actions}"
        }
    
    command = f"systemctl {action} bluetooth.service"
    try:
        result = subprocess.run(
            command.split(),
            capture_output=True,
            text=True,
            timeout=30
        )
        return {
            "success": result.returncode == 0,
            "command": command,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

if __name__ == "__main__":
    mcp.run()